package org.yu.team2023.flashdays.registries;

import io.netty.buffer.Unpooled;
import net.minecraft.core.BlockPos;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraft.network.chat.Component;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.server.level.ServerPlayer;
import net.minecraft.world.InteractionHand;
import net.minecraft.world.InteractionResult;
import net.minecraft.world.MenuProvider;
import net.minecraft.world.entity.player.Inventory;
import net.minecraft.world.entity.player.Player;
import net.minecraft.world.inventory.AbstractContainerMenu;
import net.minecraft.world.inventory.MenuType;
import net.minecraft.world.level.Level;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.phys.BlockHitResult;
import net.minecraftforge.network.NetworkHooks;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

public interface IMenuBlock {

    default InteractionResult use(BlockState pState, Level pLevel, BlockPos pPos, Player pPlayer, InteractionHand pHand, BlockHitResult pHit) {
        if (pLevel instanceof ServerLevel && pPlayer instanceof ServerPlayer serverPlayer) {
            open(serverPlayer, pPos,pState,pLevel);
        }
        return InteractionResult.sidedSuccess(!pLevel.isClientSide);
    }

    @Nullable
    MenuType<?> getMenuType(BlockState blockState,Level level,BlockPos pos);

    /**
     * 打开菜单（方块实体）
     *
     * @param player 玩家
     * @param title  标题
     * @param pos    位置
     */
    default <T extends Component> void open(Player player, T title, BlockPos pos,BlockState state,Level level) {
        var menuType=getMenuType(state,level,pos);
        if(menuType==null)return;
        if (player instanceof ServerPlayer serverPlayer) {
            MenuProvider containerProvider = new MenuProvider() {
                @Nonnull
                @Override
                public Component getDisplayName() {
                    return title;
                }

                @Override
                public AbstractContainerMenu createMenu(int containerId, @Nonnull Inventory inventory, @Nonnull Player player) {
                    FriendlyByteBuf buffer = new FriendlyByteBuf(Unpooled.buffer());
                    buffer.writeBlockPos(pos);
                    return menuType.create(containerId, inventory, buffer);
                }
            };
            NetworkHooks.openScreen(serverPlayer, containerProvider, pos);
        }
    }



    default void open(ServerPlayer player, BlockPos pos,BlockState state,Level level) {
            open(player, state.getBlock().getName(),pos,state,level);
    }
}
